const app = getApp();
const util = require('../../utils/util.js');
const key = 'RVHBZ-XL3C4-ONWUP-DDAIW-EJ3G3-RVFI4'; //使用在腾讯位置服务申请的key
const referer = '本地有小程序'; //调用插件的app的名称
const location = '';
const category = '';
const chooseLocation = requirePlugin('chooseLocation');
var QQMapWX = require("../../libs/qqmap-wx-jssdk.js");
var qqmapsdk;
Page({

    /**
     * 页面的初始数据
     */
    data: {
        addressid: '',
        address: '',
        area_list: {},
        area_list_str: '',
        city_id: '',
        area_id: '',
        picker_lng: '',
        picker_lat: '',
        area_info: '',
        true_name: '',
        mob_phone: '',
        detail_address: '',
        is_default: '',
        inDeliveryScope: true
    },
    onLoad: function (options) {
        //请求分享数据
        wx.request({
            url: app.globalData.ApiUrl + '/index.php?act=wx_share&op=get_share',
            data: {},
            method: 'GET',
            dataType: 'json',
            success: res => {
                if (res.data.code == '200') {
                    this.setData({
                        share_default_title: res.data.datas.title,
                        share_default_image_url: res.data.datas.imageUrl
                    })
                }
            }
        })
        if (options.iforder) {
            this.setData({
                iforder: options.iforder
            });
        }
        util.share();
        let self = this;
        let addressid = options.addressid;
        wx.getStorage({
            key: 'member_mobile',
            success: (res) => {
                self.setData({
                    member_mobile: res.data,
                });
            }
        });
        wx.getStorage({
            key: 'latitude',
            success: res => {
                self.setData({
                    latitude: res.data
                });
            }
        });
        wx.getStorage({
            key: 'longitude',
            success: res => {
                self.setData({
                    longitude: res.data
                });
            }
        });
        wx.getStorage({
            key: 'key',
            success: (res) => {
                self.setData({
                    key: res.data,
                });

                if (addressid) {
                    self.setData({
                        addressid: addressid,
                    });
                    wx.request({
                        url: app.globalData.ApiUrl + '/index.php?act=member_address&op=address_info',
                        data: {
                            key: res.data,
                            address_id: addressid
                        },
                        method: 'POST',
                        header: {
                            'content-type': 'application/x-www-form-urlencoded'
                        },
                        dataType: 'json',
                        success: (res) => {
                            if (res.data.code == 200) {
                                var result = res.data.datas;
                                self.setData({
                                    city_id: result.address_info.city_id,
                                    area_id: result.address_info.area_id,
                                    area_info: result.address_info.area_info,
                                    address: result.address_info.address,
                                    picker_lat: result.address_info.lat,
                                    picker_lng: result.address_info.lng,
                                    true_name: result.address_info.true_name,
                                    mob_phone: result.address_info.mob_phone,
                                    detail_address: result.address_info.detail_address,
                                    is_default: result.address_info.is_default
                                });
                            }
                        }
                    });
                }
            }
        });
    },
    onShow() {
        var self = this;
        const location = chooseLocation.getLocation();
        let area_ids = [];
        let area_info = '';
        let logistics_distance, logistics_reference_lat, logistics_reference_lng;
        wx.getStorage({
            key: 'key',
            success: (res) => {
                wx.request({
                    url: app.globalData.ApiUrl + '/index.php?act=member_address&op=get_area',
                    data: {
                        key: res.data,
                    },
                    method: 'POST',
                    header: {
                        'content-type': 'application/x-www-form-urlencoded'
                    },
                    dataType: 'json',
                    success: (res) => {
                        if (res.data.code == 200) {
                            let area_list_str = '';
                            let result = res.data.datas;
                            for (var i in result) {
                                area_list_str += result[i].area_name + '，';
                            }
                            self.setData({
                                area_list_str: area_list_str.substring(0, area_list_str.length - 1)
                            });
                            if (location) {
                                for (let i in result) {
                                    if (location.address.indexOf(result[i].area_name) != -1) {
                                        area_ids = result[i].area_ids.split('_');
                                        area_info = result[i].area_name;
                                        logistics_distance = result[i].logistics_distance;
                                        logistics_reference_lat = result[i].logistics_reference_lat;
                                        logistics_reference_lng = result[i].logistics_reference_lng;
                                    }
                                }
                                if (area_info) {
                                    self.setData({
                                        area_info: area_info,
                                        address: location.name,
                                        picker_lng: location.longitude,
                                        picker_lat: location.latitude,
                                        city_id: area_ids['1'],
                                        area_id: area_ids['2'],
                                        logistics_distance: logistics_distance,
                                        logistics_reference_lat: logistics_reference_lat,
                                        logistics_reference_lng: logistics_reference_lng,
                                    });
                                    self.verifyDistance();
                                    if (!this.data.inDeliveryScope) {
                                        wx.showModal({
                                            title: '超出配送范围！',
                                            content: '是否查看可配送范围',
                                            success: res => {
                                                if (res.confirm) {
                                                    wx.navigateTo({
                                                        url: '../delivery_area/delivery_area'
                                                    });
                                                } else {
                                                    self.chooseLocation();
                                                }
                                            }
                                        });
                                        return false;
                                    }
                                } else {
                                    self.setData({
                                        address: '',
                                        city_id: '',
                                        area_id: '',
                                        picker_lng: '',
                                        picker_lat: '',
                                        area_info: ''
                                    });
                                    wx.showToast({
                                        title: '该地址不在配送范围内，请重新选择',
                                        icon: 'none',
                                        duration: 3000
                                    });
                                }
                            }
                        }
                    }
                });
            }
        });
    },
    chooseLocation: function () {
        wx.navigateTo({
            url: `plugin://chooseLocation/index?key=${key}&referer=${referer}&location=${location}&category=${category}`
        });
    },
    verifyDistance: function () {
        var self = this;
        qqmapsdk = new QQMapWX({
            key: 'FS4BZ-HINKW-7XBRR-OLZ5Y-PLPF6-5CF5J'
        });
        qqmapsdk.calculateDistance({
            mode: 'straight',
            from: {
                latitude: self.data.picker_lat,
                longitude: self.data.picker_lng
            },
            to: [{
                latitude: self.data.logistics_reference_lat,
                longitude: self.data.logistics_reference_lng
            }],
            success: ressuc => {
                if (ressuc.result.elements[0].distance - self.data.logistics_distance * 1000 > 0) {
                    self.setData({
                        inDeliveryScope: false
                    });
                } else {
                    self.setData({
                        inDeliveryScope: true
                    });
                }
            }
        });
    },
    formSubmit: function (e) {
        if (!this.data.inDeliveryScope) {
            wx.showModal({
                title: '超出配送范围！',
                content: '是否查看可配送范围',
                success: res => {
                    if (res.confirm) {
                        wx.navigateTo({
                            url: '../delivery_area/delivery_area'
                        });
                    }
                }
            });
            return false;
        }
        var self = this;
        var uri = app.globalData.ApiUrl + '/index.php?act=member_address&op=address_add';
        var postData = {
            key: self.data.key,
            true_name: e.detail.value.true_name,
            mob_phone: e.detail.value.mob_phone,
            is_default: e.detail.value.is_default ? 1 : 0,
            city_id: self.data.city_id,
            area_id: self.data.area_id,
            address: self.data.address,
            area_info: self.data.area_info,
            lat: self.data.picker_lat,
            lng: self.data.picker_lng,
            detail_address: e.detail.value.detail_address
        };
        if (self.data.addressid) {
            postData.address_id = self.data.addressid;
            uri = app.globalData.ApiUrl + '/index.php?act=member_address&op=address_edit';
        }
        wx.request({
            url: uri,
            data: postData,
            method: 'POST',
            header: {
                'content-type': 'application/x-www-form-urlencoded'
            },
            dataType: 'json',
            success: (res) => {
                if (res.data.code == 200) {
                    wx.showToast({
                        title: '保存成功',
                        icon: 'success',
                        duration: 1000,
                        success: function () {
                            setTimeout(function () {
                                if (self.data.iforder) {
                                    wx.navigateTo({
                                        url: '../address_choose/address_choose?backPage=3&address_id=' + res.data.datas.address_id
                                    });
                                } else {
                                    wx.redirectTo({
                                        url: '../address_manage/address_manage'
                                    });
                                }

                            }, 1000);
                        }
                    });
                } else {
                    wx.showToast({
                        title: res.data.datas.error,
                        icon: 'none',
                        duration: 3000
                    });
                }
            }
        });
    },
    onShareAppMessage: function () {
        let share_key = this.data.key ? this.data.key : '';
        let share_path = '';
        if (util.getCurrentPageUrlWithArgs().indexOf("?") != -1) {
            share_path = util.getCurrentPageUrlWithArgs() + '&share_key=' + share_key;
        } else {
            share_path = util.getCurrentPageUrlWithArgs() + '?share_key=' + share_key;
        }
        return {
            title: this.data.share_default_title,
            imageUrl: this.data.share_default_image_url,
            path: share_path
        };
    }
});